package com.yeyouluo.activemq.topic;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class AppConsumer {

	private static final String url = "tcp://127.0.0.1:61616";
	private static final String topicName = "first-topic";

	public static void main(String[] args) {
		// 1.创建ConnectionFactory
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD, url);

		// 2.创建连接
		Connection connection = null;
		try {
			connection = connectionFactory.createConnection();
			// 3.启动连接
			connection.start();

			// 4.创建Session
			Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			// 5.创建Session
			Destination destination = session.createTopic(topicName);

			// 6.创建消费者
			MessageConsumer consumer = session.createConsumer(destination);

			// 7.创建一个监听器
			consumer.setMessageListener(new MessageListener() {

				@Override
				public void onMessage(Message message) {
					TextMessage textMessage = (TextMessage) message;
					try {
						System.out.println("接收消息：" + textMessage.getText());
					} catch (JMSException e) {
						e.printStackTrace();
					}
				}

			});
		} catch (JMSException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			// 关闭连接：这里注释掉的原因是，先启动消费者，让其等待（不关闭连接），再启动生产者。
			// 如果不注释掉以下代码，则生产者还没有生产消息，连接就关闭了，消费者也就无法再消费消息。
			// if (connection != null) {
			// try {
			// connection.close();
			// } catch (JMSException e) {
			// e.printStackTrace();
			// }
			// }
		}

	}

}
